<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use App\Models\Message;
use App\Models\MessageTemplate;

class MessageController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('短信列表')
            ->description('每次给用户发送的短信都会显示在这里')
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Message);

        $grid->column('id', 'ID')->sortable();
        $grid->column('mobile', '发送手机号');
        $grid->template('模板名称')->display(function ($template) {
            return $template['name'];
        });
        $grid->column('code', '短信验证码');
        $grid->column('message', '短信内容');
        $grid->column('send_at', '发送时间');
        $grid->column('overdue_at', '过期时间');
        $grid->column('is_use', '是否使用')->using([0 => '否', 1 => '是']);
        $grid->column('type', '类别')->using([1 => '模板短信', 2 => '自定义短信']);

        // 禁用新增按钮
        $grid->disableCreateButton();
        //禁用导出按钮
        $grid->disableExport();
        // 禁用显示按钮
        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
        });
        $grid->tools(function ($tools) {
            // 禁用批量删除按钮
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });

        $grid->model()->orderBy('send_at', 'desc');

        // 数据查询过滤
        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1/2, function ($filter) {
                $filter->like('mobile', '手机号');
            });
            // 添加字段过滤器
            $filter->column(1/2, function ($filter) {
                $message_template = MessageTemplate::get()->toArray();
                $message_template = array_column($message_template, 'name', 'id');
                $filter->equal('message_template_id', '模板名称')->select($message_template);
            });
        });

        return $grid;
    }
}
